<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="名称" clearable>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getRoleList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="isAuth('sys/role/add')" type="primary" @click="dialogVisible = true">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
    >
       <el-table-column width="55" label="序号">
        <template slot-scope="scope">
          <span>{{ (page - 1) * limit + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="role_name" label="角色名称" width="120">
      </el-table-column>
      <el-table-column prop="remark" label="备注" show-overflow-tooltip>
      </el-table-column>

      <el-table-column prop="statu" label="状态" v-if="isAuth('sys/role/toggle')">
        <template slot-scope="scope">
          <el-button
            type="text"
            v-if="scope.row.status === 1"
            @click="setToggle(scope.row)"
            >启用</el-button
          >
          <el-button
            type="text"
            v-if="scope.row.status === 0"
            @click="setToggle(scope.row)"
            >禁用</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('sys/role/set_func')" type="text" @click="permRole(scope.row)"
            >分配权限</el-button
          >

          <el-button v-if="isAuth('sys/role/edit')" type="text" @click="editRole(scope.row)">编辑</el-button>

          <el-button v-if="isAuth('sys/role/del')" type="text" @click="removeRole(scope.row)"
              >删除</el-button
            >
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="current"
      :page-size="size"
      :total="total"
    >
    </el-pagination> -->

    <!--新增对话框-->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editForm"
        label-width="100px"
        class="demo-editForm"
      >
        <el-form-item label="角色名称" prop="role_name" label-width="100px">
          <el-input v-model="editForm.role_name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="remark" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sort" label-width="100px">
          <el-input-number v-model="editForm.sort" :min="0" label="排序号"
            >0</el-input-number
          >
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editForm')"
            ><span v-if="editForm.role_id">确认修改</span
            ><span v-else>立即创建</span></el-button
          >
          <!-- <el-button @click="resetForm('editForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      :title="`分配权限:【${edirRoleForm.role_name}】`"
      :visible.sync="permDialogVisible"
      width="800px"
      :before-close="handleClose2"
    >
      <el-form ref="permForm" :key="getSymbol()" v-loading="Loading">
        <!-- 一级 v-loading="loading"--> 
        <div v-for="(item, index) in permTreeData" :key="index" class="preBox">
          <div class="preTitle1">
            <span>{{ item.title }}</span>
            <el-checkbox
              v-model="item.ck"
              label="全选"
              @change="setPre1($event, item)"
            ></el-checkbox>
          </div>
          <div class="preContent">
            <!-- 二级 -->
            <div
              class="preLine"
              v-for="(item2, index2) in item.children"
              :key="item2.menu_id"
            >
              <div class="left">{{ item2.title }}:</div>
              <div class="right">
                <el-checkbox
                  v-for="item3 in item2.children"
                  :label="item3.title"
                  :key="item3.menu_id"
                  @change="setPre2($event, item)"
                  v-model="item3.ck"
                  >{{ item3.title }}</el-checkbox
                >
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">取 消</el-button>
        <el-button type="primary" @click="submitPermFormHandle('permForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      page: 1,
      limit: 10,
      searchForm: {},
      edirRoleForm: {}, //当前编辑角色权限

      total: 0,
      size: 10,
      current: 1,

      dialogVisible: false,
      editForm: {},

      tableData: [],

      editFormRules: {
        role_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },

      multipleSelection: [],

      permDialogVisible: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
      permTreeData: [], //权限列表

      //
      isIndeterminate: true,
      checkAll: false,
    };
  },
  computed:{
    Loading() {
      return this.$store.state.Loading
    }
  },
  created() {
    this.getRoleList();
  },
  methods: {
    handleSizeChange(val) {
      this.size = val;
      this.getRoleList();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getRoleList();
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
      this.editForm = {};
    },
    handleClose() {
      this.resetForm("editForm");
    },

    getRoleList() {
      let data = {
        page: this.page,
        limit: this.limit,
        search: this.searchForm,
      };
      this.$axios.get("admin/role/role_list", data).then((res) => {
        this.tableData = res.data.data.list;
      });
    },
    //添加角色
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = "";
          this.editForm.role_id
            ? (url = "admin/role/edit")
            : (url = "admin/role/add");
          //   delete this.editForm.company_id
          //   delete this.editForm.is_admin
          //   delete this.editForm.status
          this.$axios.post(url, this.editForm).then((res) => {
            this.$message({
              showClose: true,
              message: "操作成功",
              type: "success",
            });
            this.getRoleList();
            this.dialogVisible = false;
            this.resetForm(formName);
          });
        } else {
          return false;
        }
      });
    },
    //设置启用禁用
    setToggle(e) {
      let text = "";
      e.status == 1
        ? (text = `确认禁用【${e.role_name}】?`)
        : (text = `确认启用【${e.role_name}】?`);
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .post("admin/role/toggle_status", { id: e.role_id })
          .then((res) => {
            this.getRoleList();
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          });
      });
    },
    //编辑角色
    editRole(data) {
      this.dialogVisible = true;
      this.editForm = JSON.parse(JSON.stringify(data));
    },
    //删除角色
    removeRole(data) {
      this.$confirm(`确认删除【${data.role_name}】角色?`, "提示", {
        type: "warning",
      }).then(() => {
        this.$axios.post("admin/role/delete", { id: data.role_id }).then(() => {
          this.$message.success("删除成功");
          this.getRoleList();
        });
      });
    },
    //获取权限列表
    permRole(e) {
      this.permDialogVisible = true;
      this.edirRoleForm = e;
      this.$axios
        .post("/admin/menu/getAllMenu", { id: e.role_id })
        .then((res) => {
          this.permTreeData = res.data.data.menu;
          // console.log(this.permTreeData);
        });
    },
    //设置权限
    setPre1(e, data) {
      data.children.forEach((item, index) => {
        if (item.children) {
          item.children.forEach((item2, index2) => {
            item2.ck = e;
          });
        }
      });
    },
    setPre2(e, data) {
      // console.log(e, data);
      // data.ck = false
      // data.children.forEach((item, index) => {
      //   if (item.children) {
      //     item.children.forEach((item2, index2) => {
      //       if (item2.ck) {
      //         data.ck = true;
      //         return;
      //       }
      //     });
      //   }
      // });
    },
    //关闭权限界面
    handleClose2() {
      this.permDialogVisible = false;
      // this.permTreeData = {};
    },
    //提交角色权限
    submitPermFormHandle() {
      let menu_ids = [] //选中的id
      let del_ids = [] //未选中的id
      this.permTreeData.forEach((item) => {
        if (item.children) {
          item.children.forEach((item2) => {
              if (item2.children) {
                item2.children.forEach((item3)=> {
                  if (item3.ck) {
                    menu_ids.push(item3.menu_id)
                  } else {
                    del_ids.push(item3.menu_id)
                  }
                })
              }
          });
        }
      });
      let data = {
        menu_ids,
        del_ids,
        role_id:this.edirRoleForm.role_id
      }
      this.$axios.post("admin/role/set_func",data).then((res) => {
        this.$message({
          showClose: true,
          message: "操作成功",
          type: "success",
        });
        this.permDialogVisible = false;
      });
      this.permDialogVisible = false;
    },
    //不重复值
    getSymbol() {
      return Symbol();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
/deep/ .el-dialog__body {
  padding: 15px;
}
.preBox {
  margin-bottom: 15px;
  border: 1px solid #ebedf6;
  .preTitle1 {
    color: #f00;
    background-color: #f8f9fc;
    display: flex;
    justify-content: space-between;
    padding: 10px 15px;
    span {
      color: #000;
      font-weight: 700;
    }
  }
  .preContent {
    padding: 15px;
    .preLine {
      display: flex;
      margin-bottom: 12px;
      font-size: 14px;
      .left {
        flex: 1;
        text-align: right;
        padding-right: 20px;
      }
      .right {
        flex: 8;
        display: flex;
        flex-wrap: wrap;
        .el-checkbox {
          width: 20%;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>